package com.singularity.common.service.impl;

import cn.dev33.satoken.exception.SaTokenException;
import cn.dev33.satoken.secure.BCrypt;
import cn.dev33.satoken.session.SaSession;
import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;

import com.singularity.common.domain.entity.User;
import com.singularity.common.mapper.UserMapper;
import com.singularity.common.domain.dto.permission.PermissionInfoDTO;
import com.singularity.common.domain.dto.role.RoleInfoDTO;
import com.singularity.common.domain.dto.user.UserInfoDTO;
import com.singularity.common.domain.enumeration.PrefixEnum;
import com.singularity.common.domain.param.user.PasswordLoginParam;
import com.singularity.common.service.LoginService;
import com.singularity.common.service.PermissionService;
import com.singularity.common.service.RoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Objects;

/**
 * @author 天
 * @description: 登录相关接口实现
 */
@Service
public class LoginServiceImpl implements LoginService {

    private final UserMapper userMapper;

    private final RoleService roleService;

    private final PermissionService permissionService;

    @Autowired
    public LoginServiceImpl(UserMapper userMapper, RoleService roleService, PermissionService permissionService) {
        this.userMapper = userMapper;
        this.roleService = roleService;
        this.permissionService = permissionService;
    }

    @Override
    public UserInfoDTO loginByPassword(PasswordLoginParam passwordLoginParam){
        String account = passwordLoginParam.getAccount();
        String password = passwordLoginParam.getPassword();
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(User::getAccount, account).isNull(User::getDeleteAt);
        User user = userMapper.selectOne(queryWrapper);
        if (Objects.isNull(user)) {
            throw new SaTokenException("该账号不存在");
        }
        if (!BCrypt.checkpw(password, user.getPassword())) {
            throw new SaTokenException("密码错误");
        }
        Integer userId = user.getId();
        String loginId = PrefixEnum.USER.getValue() + userId;
        StpUtil.login(loginId);
        //添加角色与权限
        List<RoleInfoDTO> roles = roleService.getRoleInfo(userId);
        List<PermissionInfoDTO> permissionInfoDTOList = permissionService.getPermissionInfo(roles);
        UserInfoDTO userInfoDTO = BeanUtil.copyProperties(user, UserInfoDTO.class);
        userInfoDTO.setPermissions(permissionInfoDTOList);
        userInfoDTO.setRoles(roles);
        return userInfoDTO;
    }

    @Override
    public void logout() {
        StpUtil.logout();
    }

}
